package com.infoland.afanmall.base.util;


import android.app.Activity;
import android.app.Fragment;
import android.graphics.Rect;
import android.view.View;

/**
 * <p>Detects Keyboard Status changes and fires events only once for each change.</p>
 */
public class Keyboard {
    private static final int SOFT_KEY_BOARD_MIN_HEIGHT = 100;
    private KeyboardListener mKeyBodListener;
    boolean keyboardVisible = false;

    public Keyboard registerFragment(Fragment f) {
        registerView(f.getView());
        return this;
    }

    public Keyboard registerActivity(Activity a) {
        registerView(a.getWindow().getDecorView().findViewById(android.R.id.content));
        return this;
    }

    public Keyboard registerView(final View v) {
        v.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect r = new Rect();
            v.getWindowVisibleDisplayFrame(r);
            int heightDiff = v.getRootView().getHeight() - (r.bottom - r.top);
            if (heightDiff > SOFT_KEY_BOARD_MIN_HEIGHT) { // if more than 100 pixels, its probably a keyboard...
                if (!keyboardVisible) {
                    keyboardVisible = true;
                    if (mKeyBodListener != null) {
                        mKeyBodListener.onVisibilityChanged(true);
                    }
                }
            } else {
                if (keyboardVisible) {
                    keyboardVisible = false;
                    if (mKeyBodListener != null) {
                        mKeyBodListener.onVisibilityChanged(false);
                    }
                }
            }
        });

        return this;
    }

    public Keyboard setmKeyBodListener(KeyboardListener listener) {
        mKeyBodListener = listener;
        return this;
    }

    public interface KeyboardListener {
        void onVisibilityChanged(boolean keyboardVisible);
    }

}